const { validationResult, buildCheckFunction, ValidationChain } = require('express-validator');
const { isValidObjectId } = require('mongoose');
// can be reused by many routes

// parallel processing
// 并行处理
const validate = validations => {
  return async (req, res, next) => {
    await Promise.all(validations.map(validation => validation.run(req)));

    const errors = validationResult(req);
    if (errors.isEmpty()) {
      return next();
    }

    res.status(400).json({ errors: errors.array() });
  };
};

// sequential processing, stops running validations chain if the previous one have failed.
// 顺序处理
// const validate = validations => {
//   return async (req, res, next) => {
//     for (let validation of validations) {
//       const result = await validation.run(req);
//       if (result.errors.length) break;
//     }

//     const errors = validationResult(req);
//     if (errors.isEmpty()) {
//       return next();
//     }

//     res.status(400).json({ errors: errors.array() });
//   };
// };

exports = module.exports = validate
exports.isValidObjectId = (location, field)=>{
    return buildCheckFunction(location)(field).custom(async value => {
        if(!isValidObjectId(value)){
            return Promise.reject('ID类型无效') // 异步 + async 返回 Promise
            // 同步 失败
            // throw new Error('文章ID类型错误')
        }
        // 同步 成功
        // return true
    })
}